/**
 * @Author:卿雨欣
 * @Date:20200617
 * @Describle:这是填写组合产品信息页
 */
import React, { Component } from "react";
import {Modal, Button, Input, Select, InputNumber, Form, message} from 'antd';
import axios from "axios";
import {getCookieId} from "../../../utils/GetCookie";
import {URL} from '../../../index'

//声明全局变量、常量
const { TextArea } = Input; //多文本输入框
const { Option } = Select;  // 选择框
const layout = {            // 表单页面布局
    labelCol: { span: 8 },
    wrapperCol: { span: 12 },
};
const tailLayout = {        //表单内按钮布局
    wrapperCol: { offset: 8, span: 16 },
};
const validateMessages = {  //自定义表单验证提示信息
    required: "必填项！",
    types:{
        number: '${label} is a validate number!',
    },
    number:{
        range:'${label} 必须大于 ${min} ',
    },
};
var tye="";//组合类型变量

//生成提交的成分产品，包括产品代码以及产品比例
function ratioData(tsCode,ratio){
    this.productCode = tsCode;
    this.shareRadio = ratio;
}
//生成组合，包括表单提交及验证
export default class CreatButton extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false, //包含表达的modal可见性
            visibleNo: false, //未选择产提示的modal可见性
            confirmLoading: false, //加载
            stocksShow:false, // 表单中股票产品的可见性
            fundsShow:false, // 表单中基金产品的可见性
            productRatioDtoList:[],//表单中所有的成分产品的数组
            productCode:[], //已选中的成分产品的代码数组
            comBaseCate:"",//组合类型
        };
        this.onReset.bind(this);
    }
    //展示form表单
    formRef = React.createRef();
    //处理显示产品表单还是未选择提示逻辑的函数
    showModal = (productCode) => {
        var productCode2 = [];//函数内的变量，存储选中的基金/股票的代码
        this.setState({
            productCode:productCode2,
        })
        //如果股票列表、基金列表都存在，且长度都大于0
        if(this.props.onCreat1.length>0 && this.props.onCreat2.length>0) {
            //股票列表、基金列表选中的数量都符合策略
            if (this.props.onCreat1[0].length == this.props.sharelength && this.props.onCreat2[0].length == this.props.fdShareLength) {
                tye = "混合型";
                for (let i = 0; i < this.props.onCreat1[0].length; i++) {
                    productCode2.push(this.props.onCreat1[0][i].shareTsCode)
                }
                for (let i = 0; i < this.props.onCreat2[0].length; i++) {
                    productCode2.push(this.props.onCreat2[0][i].fdShareTsCode)
                }
                // 设置弹窗的可见性
                this.setState({
                    visible: true,
                    visibleNo: false,
                    fundsShow:true,
                    stocksShow:true,
                });
            }else {
                this.setState({
                    visible: false,
                    visibleNo: true,
                    fundsShow:false,
                    stocksShow:false,
                });
            }
        }
        // 基金列表无数据，股票列表有数据
        else if(this.props.onCreat1.length>0 && this.props.fdShareLength==0){
            // 股票列表选中项符合策略规定的数量 this.props.sharelength策略规定的股票数量
            if(this.props.onCreat1[0].length == this.props.sharelength){
                tye = "股票型";
                for (let i = 0; i < this.props.onCreat1[0].length; i++) {
                    productCode2.push(this.props.onCreat1[0][i].shareTsCode)
                }
                //修改弹窗可见性，弹出表单弹窗
                this.setState({
                    visible: true,
                    visibleNo: false,
                    stocksShow:true,
                });
            }else{  //不符合则修改弹窗可见性，弹出提示
                this.setState({
                    visible: false,
                    visibleNo: true,
                    stocksShow:false,
                });
            }
        }
        // 股票列表无数据，基金列表有数据
        else if(this.props.onCreat2.length>0 && this.props.sharelength==0 ){
            // 基金列表选中项符合策略规定的数量 this.props.fdSharelength策略规定的股票数量
            if(this.props.onCreat2[0].length == this.props.fdShareLength){
                tye = "基金型";
                for (let i = 0; i < this.props.onCreat2[0].length; i++) {
                    productCode2.push(this.props.onCreat2[0][i].fdShareTsCode)
                }
                //修改弹窗可见性，弹出表单弹窗
                this.setState({
                    visible: true,
                    visibleNo: false,
                    fundsShow:true,
                });
            }else{ //不符合，则修改弹窗可见性，弹出提示
                this.setState({
                    visible: false,
                    visibleNo: true,
                    fundsShow:false,
                });
            }
        }
        else{ //不符合上述三种情况，弹出数量提示弹窗
            this.setState({
                visible: false,
                visibleNo: true,
                fundsShow:false,
                stocksShow:false,
            });
        }
        //设置组合类型状态
        this.setState({
            comBaseCate:tye,
        })
    };
    //处理表单的“确定”按钮，回调函数
    handleOk = () => {
        this.setState({
            confirmLoading: true,
            stocks:[],
            funds:[],
        });
        // 在3s后，设置状态，收回弹窗
        setTimeout(() => {
            this.setState({
                visible: false,
                confirmLoading: false,
                stocksShow:false,
                fundsShow:false,
            });
            this.onReset();
        }, 3000);
    };
    //处理表单“取消”按钮，回调函数
    handleCancel = () => {
        this.setState({
            visible: false,
            productCode:[],
            comBaseCate:"",
        });
    };
    //表单提交，回调函数
    onFinish = values => {
        var productListNew = []; //存储产品对象，包括代码、比例
        var total = 0; // 比例相加之和
        for (let i=0;i<this.state.productCode.length;i++){
            var properties = this.state.productCode[i];
            var ratio =parseFloat(values[properties])/100;
            total += ratio;
            var productObj = new ratioData(properties,ratio); // 生成新的产品比例对象
            productListNew.push(productObj);
        }
        if(total!=1){
            message.warning('组合成份的比例相加必须等于1');
        }else{
            // 获取组合名称判断结果 判断组合名称是否唯一
            axios({
                method:"GET",
                url:URL+"/combinationBaseInfo/VerifyrepeatedComName",
                params:{comName:values['comBaseName']},
            }).then(res=>{
                if(res.data.code == 500){
                    this.props.history.push('/serverError')
                }
                else if(res.data.code == 201){
                    message.warning('组合名称已被使用');
                }else{
                    //所有验证都通过，提表单内封装的数据
                    axios.post(URL+"/combinationBaseInfo/insertCombinationBaseInfo",
                        {
                            strategyId: this.props.strategyIdButton,//this.props.strategyIdButton
                            counselorId:getCookieId(),
                            comBaseName: values['comBaseName'],
                            conBaseStartMoney: values['conBaseStartMoney'],
                            comBaseDesc: "这是一个金融理财产品",
                            comBaseCate:(this.state.comBaseCate == "股票型"?1:(this.state.comBaseCate== "基金型"?2:3)),
                            comBaseRiskLevel: parseInt(values['comBaseRiskLevel']),
                            productRatioDtoList: productListNew,
                        }).then(data=>{
                        if(res.data.code == 500){
                            this.props.history.push('/serverError')
                        }
                        else if(data.data.code == 200){
                            message.success('创建成功!');
                            this.handleOk();
                        }else{
                            message.error('创建失败!');
                        }
                    }).catch(function (error) {
                    })
                }
            }).catch(error=>{
                console.log(error);
            });
        }
    };
    //处理“清除”，重置表单，回调函数
    onReset = () => {
        this.formRef.current.resetFields();
    };

    //处理“确定”按钮，回调函数
    handleOkNo = e => {
        this.setState({
            visibleNo: false,
        });
    };
    render() {
        //声明render中的变量、常量
        const {visible, confirmLoading} = this.state;
        return (
            <div>
                <Button type="primary" onClick={this.showModal} style={{marginLeft:150,marginTop:50}}>
                    生成组合
                </Button>
                <Modal
                    title="选择提示"
                    visible={this.state.visibleNo}
                    okText="确定"
                    onOk={this.handleOkNo}
                    footer={
                        <Button type="primary" onClick={this.handleOkNo}>确定</Button>
                    }
                >
                    <p>该策略股票数量为:<span style={{color:"red",fontSize:14}}> {this.props.sharelength} </span></p>
                    <p>该策略基金数量为:<span style={{color:"red",fontSize:14}}> {this.props.fdShareLength}</span> </p>
                    <p>请选择符合数量的股票和基金！</p>
                </Modal>
                <Modal
                    title="组合详情填写"
                    cancelText="取消"
                    okText="确定"
                    footer={null}
                    visible={visible}
                    onOk={this.handleOk}
                    confirmLoading={confirmLoading}
                    onCancel={this.handleCancel}
                >
                    <Form {...layout} ref={this.formRef} name="control-ref" onFinish={this.onFinish} validateMessages={validateMessages}>
                        {/*如果选择了股票列表，且通过数量验证，显示股票比例输入框*/}
                        {
                            this.state.stocksShow ? (
                                this.props.onCreat1.map((item1, index1) => {
                                        let item1_1 = Array.from(item1);
                                        return (
                                            item1_1.map((item2, index2) => {
                                                return (
                                                    <Form.Item name={item2.shareTsCode} key={item2.shareTsCode} label={item2.shareName}
                                                               rules={[{required: true},{type:'number',message:"成分产品比例必须在10%到100%之间"}]}>
                                                        <InputNumber  placeholder="请输入比例"
                                                                      min={10}
                                                                      max={100}
                                                                      formatter={value => `${value}%`}
                                                                      parser={value => value.replace('%', '')}
                                                        />
                                                    </Form.Item>
                                                )
                                            })
                                        )
                                    }
                                )
                            ) : null
                        }
                        {/* 如果选择了基金列表，且通过数量验证，显示基金比例输入框*/}
                        {
                            this.state.fundsShow ? (
                                this.props.onCreat2.map((item, index) => {
                                    let item_new = Array.from(item);
                                    return (
                                        item_new.map((item1, index1) => {
                                            return (
                                                <Form.Item name={item1.fdShareTsCode} key={item1.fdShareTsCode} label={item1.fdShareName}
                                                           rules={[{required: true},{type:'number',message:"成分产品比例必须在10%到100%之间"}]}>
                                                    <InputNumber  placeholder="请输入比例"
                                                                  min={10}
                                                                  max={100}
                                                                  formatter={value => `${value}%`}
                                                                  parser={value => value.replace('%', '')}
                                                    />
                                                </Form.Item>
                                            )
                                        })
                                    )
                                })
                            ) : null
                        }
                        <Form.Item name="comBaseCate" label="组合类型" >
                            <label>{this.state.comBaseCate}</label>
                        </Form.Item>
                        <Form.Item name="comBaseName" label="组合名称" rules={[{required: true}]}>
                            <Input placeholder="请输入组合名称"/>
                        </Form.Item>
                        <Form.Item  name="conBaseStartMoney" label="起投金额(万)" rules={[{required: true},{type:'number',min:100,message:"起投金额必须大于等于100万"}]}>
                            <InputNumber placeholder="起投金额"/>
                        </Form.Item>
                        <Form.Item name="comBaseRiskLevel" label="风险等级" rules={[{required: true}]}>
                            <Select
                                placeholder="请选择风险级别"
                                allowClear
                            >
                                <Option value="1">谨慎型</Option>
                                <Option value="2">稳健型</Option>
                                <Option value="3">平衡型</Option>
                                <Option value="4">进取型</Option>
                                <Option value="5">激进型</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item name="conBaseDesc" label="组合描述" rules={[{required: true}]}>
                            <TextArea placeholder="请输入组合描述（100字内）" allowClear maxLength="100"/>
                        </Form.Item>
                        <Form.Item {...tailLayout}>
                            <Button type="primary" htmlType="submit" >
                                确定
                            </Button>
                            <Button htmlType="button" onClick={this.onReset}>
                                清除
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}
